import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

class ScanViewModuleDemo extends StatefulWidget {

  //定义回调函数， 可以指定类型
  final Function(String) blockStr;
  // final ValueChanged<int> blockStr answerQuestion;

  const ScanViewModuleDemo({super.key,required this.blockStr});

  @override
  State<ScanViewModuleDemo> createState() => _ScanViewModuleDemoState();
}

class _ScanViewModuleDemoState extends State<ScanViewModuleDemo> {
  Barcode? result;
  QRViewController? controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: "QR");


  @override
  void reassemble() {
    // TODO: implement reassemble
    super.reassemble();
    if(Platform.isAndroid) {
      controller!.pauseCamera();
    }
    controller!.resumeCamera();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded( flex: 4,child: _buildQrView(context)),
        Expanded(flex: 1, child: FittedBox(
          fit: BoxFit.contain,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    margin:const EdgeInsets.all(8),
                     child: ElevatedButton(
                      onPressed: () async {
                        await controller?.toggleFlash();
                        setState(() {
                          
                        });
                      }, 
                      child: FutureBuilder(
                        future: controller?.getFlashStatus(), builder: (context, snapshot) {
                          return Text('闪光灯: ${snapshot.data??false}',style: TextStyle(fontSize: 28));
                        },
                      )
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.all(8),
                    child: ElevatedButton(
                      onPressed: () async {
                        await controller?.toggleFlash();
                        setState(() {
                          
                        });
                      }, 
                      child: FutureBuilder(
                        future: controller?.getCameraInfo(), 
                        builder: (context, snapshot) {
                          if(snapshot.data != null) {
                            return Text(
                              'Camera facing ${describeEnum(snapshot.data!)}',
                              style: TextStyle(fontSize: 28)
                            );
                          } else {
                            return const Text("loading");
                          }
                        },
                      )
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.all(8),
                    child: ElevatedButton(
                      onPressed: () async {
                        await controller?.pauseCamera();
                      }, 
                      child: const Text("暂停", style: TextStyle(fontSize: 28)),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.all(8),
                    child: ElevatedButton(
                      onPressed: () async {
                        await controller?.resumeCamera();
                      }, 
                      child: const Text('恢复',style: TextStyle(fontSize: 28)),
                    ),
                  )
                ],
              ),
            ],
          ),
        ))
      ],
    );
  }

  _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = (MediaQuery.of(context).size.width < 400 ||
            MediaQuery.of(context).size.height < 400)
        ? 150.0
        : 300.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 10,
          cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        if (result != null) {
          widget.blockStr(result!.code as String);
        }
      });
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    print('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}